﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Threading;

namespace MeTalker.Aide
{
    internal class ImageHelper
    {
        string gifFile;
        Panel panelGif;
        bool isPuse = true;
        public ImageHelper(string gifFile, Panel panelGif) {
            this.gifFile = gifFile;
            this.panelGif = panelGif;
        }
        
        internal void Play()
        {
            panelGif.Visible = true;
            isPuse = true;
            Bitmap animatedGif = new Bitmap(gifFile);
            Graphics g = panelGif.CreateGraphics();

            int PropertyTagFrameDelay = 0x5100;
            PropertyItem propItem = animatedGif.GetPropertyItem(PropertyTagFrameDelay);
            byte[] bytes = propItem.Value;


            FrameDimension frameDimension = new FrameDimension(animatedGif.FrameDimensionsList[0]);
            int frameCount = animatedGif.GetFrameCount(FrameDimension.Time);

            int[] delays = new int[frameCount + 1];
            int i = 0;
            for (i = 0; i <= frameCount - 1; i++)
            {
                delays[i] = BitConverter.ToInt32(bytes, i * 4);
            }

            while (isPuse)
            {
                if (!isPuse)
                    break;
                for (i = 0; i <= animatedGif.GetFrameCount(frameDimension) - 1; i++)
                {
                    animatedGif.SelectActiveFrame(frameDimension, i);
                    g.DrawImage(animatedGif, new Point(0, 0));
                    Application.DoEvents();
                    Thread.Sleep(delays[i] * 10);
                }
                Thread.Sleep(1000);
            }
            animatedGif.Dispose();
            animatedGif = null;
            panelGif.Controls.Clear();
            panelGif.Update();
            panelGif.Visible = false;
        }
        internal void Stop()
        {
            isPuse = false;
        }
    }
}
